﻿/**
 * ScreenManager.as
 * @author	Aníbal G. Hormeche 
 */

package racingGame.ui 
{
	import flash.display.MovieClip;
	import flash.display.DisplayObject;
	
	
	public class ScreenManager extends MovieClip
	{
		/**** Private Variables ****/
		
		private var _stack	:Array;
		private var _index	:int;
		
		
		/**** Public Methods ****/
		
		/**
		 * Constructor.
		 */
		public function ScreenManager() 
		{
			_stack = new Array();
			_index = -1;
		}
		
		
		/**
		 * Push a screen into the stack. This screen will be the one most visible.
		 * 
		 * @param	screen	The screen to push.
		 */
		public function push(screen :IStackableScreen) :void
		{
			if (screen is DisplayObject) {
			
				addChild(screen as DisplayObject);
			}
			else {
				
				throw new Error("ScreenManager.Push : the screen passed must be a DisplayObject!");
				return;
			}
			
			if (_index >= 0) {
				
				_stack[_index].disable();
			}
			_stack.push(screen);
			_index++;
			screen.enable();
		}
		
		
		/**
		 * Pop the last pushed screen from the stack.
		 * 
		 * @return	The just poped screen.
		 */
		public function pop() :IStackableScreen
		{
			removeChild(_stack[_index]);
			_stack[_index].disable();
			
			if (_index -1 >= 0) {
				
				_index--;
				_stack[_index].enable();
			}
			
			return _stack.pop() as IStackableScreen;
		}
		
		
		/**
		 * Retrieves the stack's top screen.
		 * 
		 * @return The last pushed screen.
		 */
		public function peek() :IStackableScreen
		{
			return _stack[_index];
		}
		
		
		/**
		 * Test if an instance of the given screen's class is already in the stack.
		 * 
		 * @param	screenClass The screen's class
		 * @return	True if the is an instance of the class within the stack, false otherwise.
		 */
		public function isPushed(screenClass :Class) :Boolean {
			
			for each(var screen :IStackableScreen in _stack) {
				
				if (screen is screenClass) {
					
					return true;
				}
			}
			return false;
		}
		
		
	}

}